import {
  BadRequestException,
  Body,
  Controller,
  Delete,
  Get,
  HttpException,
  HttpStatus,
  InternalServerErrorException,
  Param,
  ParseIntPipe,
  Post,
  Put,
  Query,
} from '@nestjs/common';
import { ItemsService } from './items.service';
import { GetItemsByIdsDto, ItemDto } from './dto/items';
import { FormDataRequest } from 'nestjs-form-data';
import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library';

@Controller('items')
export class ItemsController {
  constructor(private readonly itemsService: ItemsService) {}

  @Get()
  async getAllItems(@Query('page') page: number) {
    return await this.itemsService.getAllItems(page);
  }

  @Post('/categories')
  async createCategory(@Query('name') name: string) {
    const category = await this.itemsService.createCategory(name);

    return category;
  }

  @Get('/categories')
  async getAllCategories() {
    const categories = await this.itemsService.getAllCategories();

    return categories;
  }

  @Delete('/categories/:id')
  async deleteCategory(@Param('id', new ParseIntPipe()) id: number) {
    try {
      const count = await this.itemsService.deleteCategoryById(id);
      return { count };
    } catch (error) {
      if (error instanceof PrismaClientKnownRequestError)
        throw new HttpException(
          'Позиции привязаны к этой категории',
          HttpStatus.BAD_REQUEST,
        );

      throw new BadRequestException();
    }
  }

  @Post('/ids')
  async getAllItemsByIds(@Body() dto: GetItemsByIdsDto) {
    const items = await this.itemsService.getItemsByIds(dto.ids);

    return items;
  }

  @Post()
  @FormDataRequest()
  async createItem(@Body() dto: ItemDto) {
    const id = await this.itemsService.createItem(dto, dto.file);
    console.log('created item + ', id);
    return { id };
  }

  @Get('/categories/:id')
  async getItemsByCategoryId(@Param('id', new ParseIntPipe()) id: number) {
    const items = await this.itemsService.getByCategoryId(id);

    return items.map((item) => ({
      ...item,
      photo: item.photo.toString('base64'),
    }));
  }

  @Get('/:id')
  async getItemById(@Param('id', new ParseIntPipe()) id: number) {
    const item = await this.itemsService.getItemById(id);

    return { ...item, photo: item.photo.toString('base64') };
  }

  @Delete('/:id')
  async deleteItem(@Param('id', new ParseIntPipe()) id: number) {
    return await this.itemsService.deleteItemById(id);
  }

  @Put('/:id')
  @FormDataRequest()
  async updateItem(
    @Param('id', new ParseIntPipe()) id: number,
    @Body() dto: ItemDto,
  ) {
    const _ = await this.itemsService.updateItemById(id, dto, dto.file);

    return {};
  }
}
